#include <iostream>
#include <vector>
#include <pthread.h>
#include <unistd.h>

#define NUM 5
pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;

int cnt = 1000;

void* threadrun(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&glock);
        pthread_cond_wait(&gcond, &glock);
        std::cout << "唤醒成功," << name << "开始计算cnt: " << cnt <<std::endl;
        cnt++;
        std::cout << "计算后cnt:" << cnt << std::endl;
        pthread_mutex_unlock(&glock);
    }
    return nullptr;
}

int main()
{
    std::vector<pthread_t> threads;
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        char* name = new char[64];
        snprintf(name, 64, "thread-%d", i);
        int n = pthread_create(&tid, nullptr, threadrun, name);
        if(n != 0)
            continue;
        else
            std::cout << "线程" << name << "创建成功" << std::endl;
        threads.push_back(tid);
        sleep(1);
    }

    std::cout << "5秒后开始每隔一秒唤醒一个线程" << std::endl;
    sleep(5);

    while(true)
    {
        pthread_cond_signal(&gcond);
        std::cout << "唤醒一个线程，隔一秒..." << std::endl;
        sleep(1);
    }

    for(auto& t:threads)
    {
        pthread_join(t, nullptr);
    }

    return 0;
}

